package cn.fl.arbitration.web.apply.controller;

import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.fl.arbitration.web.apply.service.IFileUploadService;
import cn.fl.arbitration.web.apply.vo.UpLoadFileRespVo;
import cn.fl.arbitration.web.apply.vo.resp.FileUploadRespVo;
import com.alibaba.dubbo.common.utils.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileUploadController {

    @Resource
    private IFileUploadService fileUploadService;
    /**
     * 上传
     *  sdcsad
     * @return
     */
    @RequestMapping("/file/upload/image.do")
    public @ResponseBody
    FileUploadRespVo uploadImage(HttpServletRequest request, HttpServletResponse response) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            try {
                UpLoadFileRespVo upload = fileUploadService.upload("cn/fl/arbitration", multipartRequest);
                if(upload==null){
                    return new FileUploadRespVo("",0,"");
                }else{
                    return new FileUploadRespVo(upload.getName(),1,upload.getUrl());
                }
            } catch (Exception e) {
                BaseLogUtils.newLogger(e.getMessage()).error(LogExceptionEnum.API_CODE_0101,e);
                return new FileUploadRespVo("",0,"");
            }

        }
        return new FileUploadRespVo("",0,"");
    }

    /**
     * 获取文件后缀名
     * @param fileName
     * @param defaultExt 匹配不到默认
     * @return
     */
    public static String getExtention(String fileName,String defaultExt) {
        if(fileName==null){
            return "";
        }
        int pos = fileName.lastIndexOf(".");
        if(pos==-1){
            if(StringUtils.isBlank(defaultExt)){
                return "none";
            }
            return defaultExt;
        }
        return fileName.substring(pos);
    }
    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    public static String getExtention(String fileName) {
        return getExtention(fileName,"");
    }

}
